package ltd.hyangyang.rpc.core.context;

import ltd.hyangyang.rpc.common.constant.RpcConstant;
import ltd.hyangyang.rpc.core.anno.RpcScann;
import ltd.hyangyang.rpc.core.anno.ServiceReference;
import ltd.hyangyang.rpc.core.anno.EnableAutoRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.logging.Logger;

public class CustomScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {
    private ResourceLoader resourceLoader;

    private static final String PROPERTIES_BASE_PACKAGE = "basePackage";

    Logger logger = Logger.getGlobal();

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        //加载ResourceLoader
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {
        //从AnnotationMetadata中获取添加了@Import注解的注解信息
        Map<String, Object> attributeMap = annotationMetadata.getAnnotationAttributes(RpcScann.class.getName());

        AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(attributeMap);

        //获取注解中的属性的值
        String[] basePackage = annotationAttributes.getStringArray(PROPERTIES_BASE_PACKAGE);

//        String basePackage = array[0];

        //初始化包扫描器
        CustomScanner registryScanner = new CustomScanner(registry, EnableAutoRegistry.class);
        CustomScanner springBeanScanner = new CustomScanner(registry, Component.class);
//        CustomScanner discoverScanner = new CustomScanner(registry, ServiceReference.class);
        registryScanner.setResourceLoader(resourceLoader);
        springBeanScanner.setResourceLoader(resourceLoader);
//        discoverScanner.setResourceLoader(resourceLoader);

        int registryCount = registryScanner.scan(basePackage);
//        int discoverCount = discoverScanner.scan(basePackage);
        int springCount = springBeanScanner.scan(RpcConstant.DEFAULT_BASE_PACKAGE);
        logger.info("实例化的携带ServiceRegistry注解的Bean的数量："+registryCount);
//        logger.info("实例化的携带ServiceDiscover注解的Bean的数量："+discoverCount);

        logger.info("实例化的spring中的bean数量："+springCount);
//        ImportBeanDefinitionRegistrar.super.registerBeanDefinitions(importingClassMetadata, registry);
    }
}
